/**
 * 数据库客户端
 *
 * Created by snowingsea on 2020/01/20.
 */
const mongoose = require('mongoose');
const debug = require('debug')('phoenix:mongo');
const logger = require('../logger');
mongoose.Promise = global.Promise;

/**
 * 连接数据库
 * @return {Promise}
 */
function connect() {
  return new Promise((resolve, reject) => {
    const {
      host,
      port,
      name,
      auth,
    } = global.config.storage.mongo;
    const { username, password } = auth;
    const uri = `mongodb://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${host}:${port}/${name}`;
    const infoURI = `mongodb://${username}@${host}:${port}/${name}`;
    debug('Start connect mongodb...');
    const options = {
      useNewUrlParser: true,
      useCreateIndex: true,
      useUnifiedTopology: true,
      useFindAndModify: false,
      maxPoolSize: 100,
    };
    mongoose.connect(uri, options)
      .then(() => {
        debug('Successfully Connect to MongoDB(%s)', infoURI);
        resolve();
      })
      .catch((err) => {
        logger.error(`Failed to connect to MongoDB(${infoURI}): ${err}`);
        debug('The connection will be tried again in 10 seconds...');
        setTimeout(() => {
          connect().then(resolve).catch(reject);
        }, 10000);
      });
  });
}

/**
 * 断开数据库连接
 * @return {Promise}
 */
function disconnect() {
  return mongoose.disconnect();
}

/**
 * Export model definition object.
 */
module.exports = {
  connect,
  disconnect,
};
